package com.kg.fiber.web;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.io.Files;

@Controller
@RequestMapping("/log")
@ResponseBody
public class LogController {
		
	@RequestMapping(value = "/list.do")
	public List<String> getStoreFiles() {
		
		List<String> fs = Lists.newLinkedList();
		
		File path = new File("fiber_logs");
		if(path.exists() && path.isDirectory()) {
		
			File[] files = path.listFiles();
			if(files != null && files.length > 0) {
				for(File f : files)
					fs.add(f.getName());
			}
		}
		
		// 按照时间顺序
		Collections.sort(fs, new Comparator<String>() {
		    @Override
		    public int compare(String o1, String o2) {
		        return o1.compareTo(o2);
		    }
		});
		
		return fs;
	}
	
	@RequestMapping(value = "/download.do//{filename}")
	public void downloadStoreFile(
			HttpServletRequest request, 
			HttpServletResponse response, 
			@PathVariable String filename) throws Exception {
		
		File file = new File("fiber_logs" + File.separator + filename);
		if(!file.exists()) {
			return;
		}
        
        response.setContentType("text/plain"); //设置返回的文件类型
        response.setCharacterEncoding("UTF-8");
        Files.copy(file, response.getOutputStream());  

        
	}
	
}
